<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="input" type="text" placeholder="输入城市名或拼音">
    </div>
    <div v-show="keyword" ref="wrapper" class="list-search">
      <ul>
        <li class="item" v-for="item in list" :key="item.id" @click="handCityClick(item.name)">{{item.name}}</li>
        <li class="item" v-show="isShow">没有查询到匹配的数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
  // 引入better-scroll
  import Bscroll from 'better-scroll'
  export default {
    name: 'Search',
    props: {
      cities: Object
    },
    data () {
      return {
        keyword: '',
        timer: null,
        list: [] // 用来存储查询到的城市
      }
    },
    computed: {
      isShow () {
        return !this.list.length
      }
    },
    methods: {
      handCityClick (city) {
        this.$store.dispatch('changeCity', city)
        // console.log(city)
        this.$router.push('/')
      }
    },
    watch: {
      keyword () {
        // 函数截流
        if (this.timer) {
          clearTimeout(this.timer)
        }
        if (!this.keyword) {
          this.list = []
          return
        }
        this.timer = setTimeout(() => {
          const result = []
          for (let i in this.cities) { // 循环的是传递过来的城市对象
            this.cities[i].forEach((value) => {
              if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
                result.push(value)
              }
            })
          }
          this.list = result
        }, 100)
      }
    },
    mounted () {
      this.scroll = new Bscroll(this.$refs.wrapper)
    }
  }
</script>
<style lang="stylus" scoped>
  .search{
    height:.44rem;
    background-color :#00bcd4;
    padding:0 .1rem;
    box-sizing border-box
    .input{
      box-sizing border-box
      width:100%;
      border-radius :.04rem;
      height:.3rem;
      margin:.1rem 0;
      text-align center
      padding :0 .1rem;
      color:#666;
    }
  }
  .list-search{
    overflow hidden
    position absolute
    top:.87rem;
    left:0;
    right:0;
    bottom:0;
    background-color:#eaeaea;
    z-index 1
    .item{
      padding-left :.1rem;
      line-height :.28rem;
      border-bottom :.01rem solid #cacaca
      background-color white
    }
  }
  .search-box{
    overflow hidden
  }
</style>
